package grpc

import (
	"context"
	"online-retailers/internal/models/dao"
	"online-retailers/internal/models/services"
	user1 "online-retailers/internal/proto/user"
)

type UserServer struct {
	user1.UnimplementedRegisterServerServer
}

func (s *UserServer) Register(ctx context.Context, req *user1.RegisterReq) (*user1.RegisterResp, error) {
	user := dao.User{
		Name: req.Name,
	}
	err := services.CreateUser(user)
	if err != nil {
		return &user1.RegisterResp{
			Code: -1,
			Msg:  "创建用户失败",
		}, err
	}
	resp := &user1.RegisterResp{
		Code: 200,
		Msg:  "创建用户成功",
	}
	return resp, err
}

func (s *UserServer) AddGoods(ctx context.Context, req *user1.AddGoodsReq) (*user1.AddGoodsResp, error) {
	goods := dao.Goods{
		Name:  req.Name,
		Price: int(req.Price),
		State: int(req.State),
		Img:   req.Img,
	}
	err := services.AddGoods(goods)
	if err != nil {
		return &user1.AddGoodsResp{
			Code: -1,
			Msg:  "添加商品失败",
		}, err
	}
	resp := &user1.AddGoodsResp{
		Code: 200,
		Msg:  "添加商品成功",
	}
	return resp, err
}

func (s *UserServer) AddPay(ctx context.Context, req *user1.AddPayReq) (*user1.AddPayResp, error) {
	pay := dao.Payment{
		UserId:  int(req.UserId),
		GoodsId: int(req.GoodsId),
		Way:     int(req.Way),
	}
	err := services.AddGoodsPay(pay)
	if err != nil {
		return &user1.AddPayResp{
			Code: -1,
			Msg:  "添加支付失败",
		}, err
	}
	resp := &user1.AddPayResp{
		Code: 200,
		Msg:  "添加支付成功",
	}
	return resp, err
}

func (s *UserServer) AddOrder(ctx context.Context, req *user1.AddOrderReq) (*user1.AddOrderResp, error) {
	order := dao.Order{
		UserId:  int(req.UserId),
		GoodsId: int(req.GoodsId),
		Way:     int(req.Way),
		Price:   int(req.Price),
		Num:     int(req.Num),
	}
	err := services.CreateOrder(order)
	if err != nil {
		return &user1.AddOrderResp{
			Code: -1,
			Msg:  "添加订单失败",
		}, err
	}
	resp := &user1.AddOrderResp{
		Code: 200,
		Msg:  "添加订单成功",
	}
	return resp, err
}

func (s *UserServer) List(ctx context.Context, req *user1.ListReq) (*user1.ListResp, error) {
	list, err := services.OrderList(int(req.UserId), int(req.Page), int(req.PageSize))
	if err != nil {
		return &user1.ListResp{
			Code: -1,
			Msg:  "列表展示失败",
			Data: nil,
		}, err
	}
	var userList []*user1.UserInfo
	for _, v := range list {
		userList = append(userList, &user1.UserInfo{
			UserId:  int32(v.UserId),
			GoodsId: int32(v.GoodsId),
			Way:     int32(v.Way),
			Price:   int32(v.Price),
			Num:     int32(v.Num),
		})
	}
	resp := &user1.ListResp{
		Code: 200,
		Msg:  "列表展示成功",
		Data: userList,
	}
	return resp, err
}
